package com.xsb.mvvmlibrary.base

import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders

/**
 *     author : 薛少博
 *     e-mail : xsb@zlhopesun.com
 *     time   : 2021/5/19
 *     desc   : 类说明
 */
abstract class BaseVmActivity<V : ViewDataBinding, VM : BaseViewModel> : BaseActivity() {
    protected lateinit var mViewModel: VM
    protected lateinit var viewDataBind: V
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewDataBind = DataBindingUtil.setContentView(this, layoutRes())
        performDataBinding()
        initView()
        initData()
        createObserver()
        getBindingVariable()
        registerUiChange()
    }

    abstract fun createObserver()

    abstract fun viewModelClass(): Class<VM>

    abstract fun getBindingVariable(): Int

    fun performDataBinding() {
        mViewModel = ViewModelProvider(this).get(viewModelClass())
        //关联ViewModel
        viewDataBind.setVariable(getBindingVariable(), mViewModel)
        //支持LiveData绑定xml，数据改变，UI自动会更新
       // viewDataBind.lifecycleOwner = this
        //让ViewModel拥有View的生命周期感应
       // lifecycle.addObserver(mViewModel)
        //viewDataBind.executePendingBindings()
    }

    open fun initView() {

    }

    open fun initData() {

    }

    private fun registerUiChange() {
        //显示弹窗
        mViewModel.showDialog.observe(this, Observer {
            showProgressDialog(
                if (it.isEmpty()) {
                    "请求网络中..."
                } else
                    it
            )
        })
        //关闭弹窗
        mViewModel.hideDialog.observe(this, Observer {
            if (it)
                hideProgressDialog()
        })
    }
}